package com.bruce.algorithm.leetcode.linklist;

/**
 * @author luotuan
 * @url https://leetcode-cn.com/problems/reverse-linked-list/
 * @Description 206. 反转链表  递归实现
 * @create 2020-07-18 10:46
 **/
public class ReverseList {
    public static ListNode reverseList(ListNode head) {
        if(head == null || head.next==null) return head;
        ListNode newNode = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newNode;
    }

    public static ListNode reverseList2(ListNode head) {
        if(head == null || head.next==null) return head;
        ListNode newHead = null;
        ListNode tmp = null;
        while (head!=null){
            tmp = head.next;
            head.next = newHead;
            newHead = head;
            head = tmp;
        }
        return newHead;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(5);
        ListNode node2 = new ListNode(4);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(2);
        ListNode node5 = new ListNode(1);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        ListNode result = reverseList2(node1);
        while (result!=null){
            System.out.print(result.val+",");
            result = result.next;
        }
    }
}
